import {
  Component, OnInit, ViewEncapsulation, ViewChild, AfterViewInit, NgZone, Renderer2,
  DoCheck, ChangeDetectionStrategy
} from '@angular/core';
import { DxTreeListComponent } from 'devextreme-angular';
import { CategotyNode, ProductNode, PriceNode, Node } from './node';

@Component({
  selector: 'app-tree-list-real',
  templateUrl: './index.html',
  styleUrls: ['./index.scss'],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TreeListRealDemoComponent implements OnInit, AfterViewInit, DoCheck {

  @ViewChild('tree')
  tree: DxTreeListComponent;
  dataSources: Node[] = [];

  constructor(private _zone: NgZone, private _renderer2: Renderer2) {

  }

  ngOnInit(): void {
    this.dataSources = this._initNodes();
  }

  ngDoCheck(): void {
    console.log('ngDocheck-tree');
  }

  ngAfterViewInit(): void {
    this._zone.runOutsideAngular(() => {
      this.tree.onRowPrepared.subscribe(this.onRowPrepared.bind(this));
    });
  }

  public onRowPrepared(e: any) {
    if (e.rowType !== 'data') {
      return;
    }

    const rowEle = e.rowElement as HTMLElement;
    const rowClass = this._getRowClassDynamic(e.data);
    if (!!rowClass) {
      rowEle.classList.add(rowClass);
    }

    if (e.data.nodeType === 0) {
      setTimeout(() => {
        this._dealCategoryRow(rowEle);
      }, 0);
    }
  }

  private _dealCategoryRow(rowEle: HTMLElement) {
    const cells = Array.from(rowEle.querySelectorAll('td')) as HTMLElement[];
    const totalCols = cells.reduce((pre, cur) => {
      const col = cur.getAttribute('colspan') || '1';
      return pre + (+col);
    }, 0);
    cells[0].setAttribute('colspan', totalCols.toString());

    const mainCellContent = cells[0].querySelector('.dx-treelist-text-content');
    if (!mainCellContent) {
      return;
    }

    cells.forEach((cell, index) => {
      if (index === 0) {
        return;
      }

      cell.style.width = '0px';
      const categoryRow = cell.querySelector('.category-row');
      if (!!categoryRow) {
        this._renderer2.setProperty(mainCellContent, 'innerText', '');
        if (mainCellContent.children.length > 0) {
          this._renderer2.removeChild(mainCellContent, mainCellContent.children[0]);
        }

        this._renderer2.appendChild(mainCellContent, categoryRow);
      }
    });
  }

  private _getRowClassDynamic(data: Node) {
    return data.nodeType === 0 ? 'category-row' + data.id : 'data-row';
  }

  private _initNodes(): Node[] {
    const ct1 = new CategotyNode('C1', 'CategotyNode_1', 'red', 'green');
    const ct2 = new CategotyNode('C2', 'CategotyNode_2', 'blue', 'white');
    ct2.parentId = ct1.id;
    const pt1 = new ProductNode('PD1', 'C1', 'Product_1', 'exchange_1');
    const pt2 = new ProductNode('PD2', 'C2', 'Product_2', 'exchange_2');
    const pt3 = new ProductNode('PD3', undefined, 'Product_3', 'exchange_3');
    const pr11 = new PriceNode('PR1', 'PD1', 'Price_1', 'price_exchange_1');
    const pr12 = new PriceNode('PR2', 'PD1', 'Price_2', 'price_exchange_2');
    const pr13 = new PriceNode('PR3', 'PD1', 'Price_3', 'price_exchange_3');
    const pr21 = new PriceNode('PR4', 'PD2', 'Price_4', 'price_exchange_4');
    const pr22 = new PriceNode('PR5', 'PD2', 'Price_5', 'price_exchange_5');
    const pr23 = new PriceNode('PR6', 'PD2', 'Price_6', 'price_exchange_6');

    return [ct1, ct2, pt1, pt2, pt3, pr11, pr12, pr13, pr21, pr22, pr23];
  }
}


